package com.lishu.carsafe.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.lishu.carsafe.R;
import com.lishu.carsafe.constant.UserPreferences;
import com.lishu.carsafe.http.HttpBase;
import com.lishu.carsafe.http.HttpLoader;
import com.lishu.carsafe.model.BaseModel;
import com.lishu.carsafe.model.UploadFileModel;
import com.lishu.carsafe.model.entity.Id;
import com.lishu.carsafe.model.entity.Vehicle;
import com.lishu.carsafe.model.entity.VehicleId;
import com.lishu.carsafe.task.Upgrade;
import com.lishu.carsafe.utils.TimeUtil;
import com.lishu.carsafe.utils.ToastUtil;
import com.lishu.carsafe.widget.DialogUtil;
import com.lishu.carsafe.widget.SpinnerNaturePopWindow;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    private long exitTime = 0;
    private SpinnerNaturePopWindow mMenuPopWindow;
    private ImageView title_left;
    private LinearLayout title_left_layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initData();
        checkPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
    }

    private void initView() {
        setTopTitle(R.string.app_name);
        setTopLeft(R.drawable.setting);

        //菜单下拉选择列表
        mMenuPopWindow = new SpinnerNaturePopWindow(this, new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                VehicleId menuId = (VehicleId) parent.getItemAtPosition(position);
                goMenuFunctionById(menuId.getId());
                mMenuPopWindow.dismiss();
            }
        });
        findViewById(R.id.title_layout).setBackgroundColor(getResources().getColor(R.color.main_color));
        title_left = findViewById(R.id.title_left);
        title_left.setOnClickListener(this);
        title_left_layout = findViewById(R.id.title_left_layout);
    }


    private void initData() {
        List<VehicleId> menuList = new ArrayList<>();
        VehicleId menu1 = new VehicleId();
        menu1.setId("1");
        menu1.setName("修改密码");
        VehicleId menu2 = new VehicleId();
        menu2.setId("2");
        menu2.setName("退出登录");
        menuList.add(menu1);
        menuList.add(menu2);
        mMenuPopWindow.setData(menuList);
    }

    private void goMenuFunctionById(String menuId) {
        if("1".equals(menuId)){//修改密码
            startActivity(new Intent(MainActivity.this, ChangePwdActivity.class));
        }else{//退出登录
            DialogUtil.showLogoutDialog(mContext, new DialogUtil.OnOkButtonClickListener() {
                @Override
                public void onOkButtonClick() {
                    //logout();
                    UserPreferences.getInstance().logout();
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    finish();
                }
            });
        }
    }

    protected void onRequestPermissionsGranted(int requestCode) {
        if (requestCode == 100) {
            try {
                new Upgrade(this, false).updateVersion();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left:
                mMenuPopWindow.setWidth(title_left_layout.getWidth());
                mMenuPopWindow.showAsDropDown(title_left);
                break;
            case R.id.my_schedule_layout:
                startActivity(new Intent(this, ScheduleActivity.class));
                break;
            case R.id.task_layout:
                startActivity(new Intent(this, TaskActivity.class));
                break;
            case R.id.monitor_layout:
                startActivity(new Intent(this, MonitorActivity.class));
                break;
            case R.id.fault_layout:
                startActivity(new Intent(this, FaultActivity.class));
                break;
            case R.id.contact_layout:
                startActivity(new Intent(this, ContactListActivity.class));
                break;
            case R.id.statistics_layout:
                startActivity(new Intent(this, StatisticsActivity.class));
                //sendApkFile("D:\\androidCode\\rgl\\safety\\app\\release\\安全员V1.0.1.apk");
                //sendApkFile("/storage/emulated/0/Download/SafeV1.0.1.apk");//"/file/uploadfiles/softwareversion/2020-06-22/20200622153236_dfb0045053ca425b94d2c125e617f292.apk"
                break;
            default:
                break;
        }
    }

    private void sendApkFile(String path) {
        HttpLoader.uploadFile("softwareversion", path, new HttpBase.IResponseListener() {
            @Override
            public void onResponse(BaseModel model) {
                if (model == null) {
                    hide();
                    ToastUtil.showShort(R.string.please_check_network);
                    return;
                }
                if (!model.success()) {
                    hide();
                    ToastUtil.showShort(getString(R.string.get_data_fail) + model.getMsg());
                    return;
                }
                UploadFileModel uploadFileModel = (UploadFileModel) model;
                if (uploadFileModel != null) {
                    String uploadedApkUrl = uploadFileModel.getData();
                    submitVersion("V1.1.0", "4", uploadedApkUrl, new Id("4"),"修复已知问题，增加密码修改功能");
                }
            }
        });
    }

    private void submitVersion(String versionNo, String versionCode, String downloadUrl, Id id, String remark) {
        HttpLoader.addVersion(versionNo, versionCode, downloadUrl, id, remark, new HttpBase.IResponseListener() {
                    @Override
                    public void onResponse(BaseModel model) {
                        if (model == null) {
                            ToastUtil.showShort(R.string.please_check_network);
                            return;
                        }
                        if (!model.success()) {
                            ToastUtil.showShort(getString(R.string.get_data_fail) + model.getMsg());
                            return;
                        }

                        ToastUtil.showShort("提交成功！");
                    }
                });
    }

    private void logout(){
        UserPreferences.getInstance().logout();
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtil.showShort("再按一次退出");
                exitTime = System.currentTimeMillis();
            } else {
                logout();
            }
            return false;
        }

        return super.onKeyDown(keyCode, event);
    }
}
